# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField
from apps.rms.models import ProtocolType, ProtocolField
from rest_framework import serializers


class ProtocolTypeSerializer(CustomModelSerializer):
    """
    网络协议-序列化器
    """
    product = BaseNameWritableRelatedField()
    field_count = serializers.SerializerMethodField(read_only=True)

    def get_field_count(self, instance):
        return len(ProtocolField.objects.filter(protocol=instance.id))

    class Meta:
        model = ProtocolType
        fields = "__all__"
        read_only_fields = ["id"]

class ProtocolFieldSerializer(CustomModelSerializer):
    """
    协议字段-序列化器
    """
    product = BaseNameWritableRelatedField()
    protocol = BaseNameWritableRelatedField()

    class Meta:
        model = ProtocolField
        fields = "__all__"
        read_only_fields = ["id"]

class ProtocolFieldBindingSerializer(CustomModelSerializer):
    """
    协议字段-序列化器
    """
    product = BaseNameWritableRelatedField()
    protocol = BaseNameWritableRelatedField()

    class Meta:
        model = ProtocolField
        fields = ['name','desc','protocol','product']
        read_only_fields = ["id"]

class ProtocolTreeSelectSerializer(CustomModelSerializer):
    """
    树型协议字段-序列化器
    """
    children=serializers.SerializerMethodField()

    def get_children(self,instance):
        queryset = ProtocolField.objects.filter(protocol=instance.id)
        return ProtocolFieldSerializer(queryset,many=True,request=self.request).data

    class Meta:
        model=ProtocolType
        fields=('id','name','children')
        read_only_fields=["id"]